#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time: 2019/4/13  12:52
# @Author: 余浪人
# @email: yulangren520@gmail.com
import os
from flask import request, jsonify
from flask_login import login_required
from apps.cms import cms_bp
from apps.lib.public import get_uuid_16, get_date_str, log
from apps.setting import Config, ProductionConfig
from apps import get_sys_uri


# 文件上传
@cms_bp.route('/upload', endpoint='upload', methods=['POST'])
@login_required
def upload_file():
    error, fileCls = '', ''
    image = ['gif', 'jpg', 'jpeg', 'png', 'bmp']
    flash = ['swf', 'flv']
    media = ['swf', 'flv', 'mp3', 'wav', 'wma', 'wmv', 'mid', 'avi', 'mpg', 'asf', 'rm', 'rmvb']
    files = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'htm', 'html', 'txt', 'zip', 'rar', 'gz', 'bz2']
    dir = request.args.get('dir')
    if request.method == 'POST':
        file = request.files['imgFile']
        filename, fext = os.path.splitext(file.filename)  # fext 为文件格式
        rnd_name = '%s%s' % (get_uuid_16(), fext)  # 文件名字
        if dir == 'image':  # 图片
            if fext.split('.')[1].lower() in image:
                fileCls = "images/"
        elif dir == 'flash':  # 动画
            if fext.split('.')[1].lower() in flash:
                fileCls = "flash/"
        elif dir == 'media':  # 音视频
            if fext.split('.')[1].lower() in media:
                fileCls = "medias/"
        else:  # 文件
            if fext.split('.')[1].lower() in files:
                fileCls = "files/"
        base_path = os.path.join(get_sys_uri(), 'apps')
        if fileCls:
            relative_path = os.path.join(Config.FILE_PATH, fileCls, get_date_str(), rnd_name).replace('\\', '/')  # 相对路径
            abs_path = (base_path + '/static/' + relative_path).replace('\\', '/')  # 拼接路径
            dirName = os.path.dirname(abs_path)
            if not os.path.exists(dirName):
                try:
                    os.makedirs(dirName)
                except:
                    error = '创建目录失败!'
            elif not os.access(dirName, os.W_OK):
                error = '没有写入权限!'
            if not error:
                file.save(abs_path)
                return jsonify({"error": 0, "url": '/' + relative_path})
    return jsonify({"error": 1, "message": "上传错误!"})


# 图片上传
@cms_bp.route('/upload_img', endpoint='upload_img', methods=['POST'])
@login_required
def upload():
    error = ''
    img_s = ['png', 'jpg', 'jpeg', 'bmp']  # 允许上传图片文件类型
    if request.method == 'POST':
        file = request.files['file']
        fname, fext = os.path.splitext(file.filename)  # fext 为文件格式
        rnd_name = '%s%s' % (get_uuid_16(), fext)  # 文件名字
        if fext.split('.')[1].lower() in img_s:  # 判断文件类型
            fileCls = "images/"
            base_path = os.path.join(get_sys_uri(), 'apps')
            relative_path = os.path.join(Config.FILE_PATH, fileCls, get_date_str(), rnd_name).replace('\\', '/')  # 相对路径
            abs_path = (base_path + '/static/' + relative_path).replace('\\', '/')  # 拼接路径
            # 检查路径是否存在，不存在则创建
            dirName = os.path.dirname(abs_path)
            if not os.path.exists(dirName):
                try:
                    os.makedirs(dirName)
                except:
                    error = '创建目录失败!'
            elif not os.access(dirName, os.W_OK):
                error = '没有写入权限!'
            if not error:
                file.save(abs_path)
                log('上传文件')
                return jsonify({"status": 0, "img_url": '/' + relative_path})
    else:
        error = '未知请求错误!'  # 请求错误
        return jsonify({"status": 1, "message": error})
